import { DialogRef, useDialog } from "../../../utils/react-use/useDialog";
import { Avatar } from "../../../components/avatar/avatar";
import { Drawer, H3, Icon, Input, Table } from "tea-component";
import { isWin, sleep } from "../../../utils/tools";
import _ from 'lodash';
import { getGroupMemberList } from "../../../api";
import React, { useEffect, useRef, useState } from "react";
import { debounce } from "lodash";

import "./member-list-drawer.scss";
import timRenderInstance from "../../../utils/timRenderInstance";
import {Menu, Item, animation, theme, contextMenu } from "react-contexify";
import { useDispatch, useSelector } from "react-redux";
import { updateUserInfo } from "../../../store/actions/user";

const { scrollable } = Table.addons;
const RIGHT__Head_LIST = [{
  id: 'tomanager',
  text: '设为管理员'
},{
  id: 'tonormal',
  text: '设为普通群员'
},{
  id: 'forbiden',
  text: '禁言'
},{
  id: 'noforbiden',
  text: '取消禁言'
},{
  id: 'alloutGroup',
  text: '踢出&撤回所有消息'
} ];

export interface GroupMemberListDrawerRecordsType {
  groupId: string;
}

export const GroupMemberListDrawer = (props: { onSuccess?: () => void;popupContainer?: HTMLElement;
   dialogRef: DialogRef<GroupMemberListDrawerRecordsType>;userIdentity?:number; }): JSX.Element => {
  const height = window.innerHeight - 77 - (isWin() ? 30 : 0);
  const { dialogRef, popupContainer,userIdentity } = props;

  const [visible, setShowState, defaultForm] =
    useDialog<GroupMemberListDrawerRecordsType>(dialogRef, {});
  const ref = useRef({firstCall: true}); 
  const dispatch = useDispatch();
  const [memberList, setMemberList] = useState([]);
  const [nextSeq, setNextSeq] = useState(0);
  const [loading, setLoading] = useState(false);
  const [isEnd,setIsEnd] = useState(false);
  const [serchVal,setSerchVal] = useState("");
  const LIST_MENU_HEAD = 'LIST_MENU_HEAD';
  const [rightClickMenuHead, setrightClickMenuHead] = useState(RIGHT__Head_LIST);
  const {userId:selfUserId} = useSelector((state: State.RootState) =>{
    return  state.userInfo;});
  const getMemberList = async (seq: number,isforce:boolean =false) => {
    if(isforce){
      setMemberList([]);
    }else if(isEnd){
      return
    }
    try {
      setLoading(true);
      const res = await getGroupMemberList({
        groupId: defaultForm.groupId,
        nextSeq: seq,
      });
      const {
        group_get_memeber_info_list_result_info_array: userList,
        group_get_memeber_info_list_result_next_seq: newNextSeq,
      } = res;
      if(newNextSeq === 0){
        setIsEnd(true)
      }
      setMemberList((pre) =>{
         let array= _.differenceBy([...pre, ...userList]);
         array.sort((a,b)=>{ 
            return  b.group_member_info_member_role-a.group_member_info_member_role;});
         return array
      });
      setNextSeq(newNextSeq);
    } catch (e) {
      console.log(e);
    }
    setLoading(false);
  };
  const onClose = () => {
    setShowState(false);
  };
const handleContextMenuHead = async (e, userMember: any) => {
    e.preventDefault();
    let rightMenus = RIGHT__Head_LIST;
    if(userIdentity<=userMember.group_member_info_member_role) return;
    if(userMember.group_member_info_member_role>200){
        rightMenus = rightMenus.filter(item =>  item.id !== 'tomanager');
    }else{
        rightMenus = rightMenus.filter(item => item.id !== 'tonormal');
    }   
    if(userMember.group_member_info_shutup_time < 0){
      rightMenus = rightMenus.filter(item =>  item.id !== 'forbiden');
    }else{
        rightMenus = rightMenus.filter(item => item.id !== 'noforbiden');
    } 
    setrightClickMenuHead(rightMenus);
    contextMenu.show({
      id: LIST_MENU_HEAD, event: e,
      props: {
          data: {
              userId: userMember.group_member_info_identifier,
              message: userMember
          }
      }
    })
  }
  const columns = [
    {
      header: "",key: "member", render: (record: any) => {
        return (
          <div className="member-list-drawer--item" onContextMenu={(e) => handleContextMenuHead(e, record) }>
            <Avatar url={record.group_member_info_face_url}  nickName={record.group_member_info_remark||record.group_member_info_nick_name}
              userID={record.group_member_info_identifier} />
            <span className="member-list-drawer--item__name">
              {record.group_member_info_remark||record.group_member_info_nick_name }
            </span> { 
               record.group_member_info_member_role === 400 ? ( <span className="member-list-drawer--item__owner">群主</span>):
              (record.group_member_info_member_role === 300&& ( <span className="member-list-drawer--item__owner">管理员</span>))
            }
          </div>
        );
      },
    },
  ];

  const onScrollBottom = () => {
    if (loading || nextSeq === 0) {
      return;
    }
    getMemberList(nextSeq);
  };

  useEffect(() => {
    if(ref.current.firstCall && visible) {
      ref.current.firstCall = false;
      getMemberList(0);
    }
  }, [visible]);
  const handlRightClick = async (e, id) => {
    const { data } = e.props;
    dispatch(updateUserInfo({
        userId:selfUserId,
        actioninf:{id,userId: data.userId}
    }));
    await sleep(1000)
    setValue(serchVal);
  } 
  const setValue = async (value) => {
    setSerchVal(value);
    if (!value?.length) {
      getMemberList(0,true);
      return;
    }
    let param  = {
      searchParams: {
        group_search_member_params_groupid_list: [ defaultForm.groupId], //必填
        group_search_member_params_keyword_list: [value],//必填
        group_search_member_params_field_list: [0,2,4]//必填
      },
      data: ''//选填
  }
  const {code,desc,json_param} = await timRenderInstance.TIMGroupSearchGroupMembers(param);
  if(code==0){
    setIsEnd(true)
    setMemberList(json_param[0].group_search_member_result_menber_info_list);
  }
 };
  const handleInoputOnchange = debounce(setValue, 300);
  return (
    <Drawer  visible={visible}  title={
        <div className="member-list-drawer--title">
          <H3>群成员</H3>
          <div className="search-box">
            <Icon type="search" className="search-icon" />
            <Input type="search" className="search-input" value={serchVal} placeholder="查找群成员" onChange={handleInoputOnchange}/>
          </div>
        </div>
      } className="member-list-drawer" popupContainer={popupContainer}  onClose={onClose} >

      <Table hideHeader disableHoverHighlight className="member-list-drawer--table"  bordered={false}
        columns={columns} records={memberList}  addons={[
          scrollable({
            virtualizedOptions: { height,  itemHeight: 60,  onScrollBottom },
          }),
        ]}
      />
      <Menu  id={LIST_MENU_HEAD}  theme={theme.light}  animation={animation.fade}>
        {
            rightClickMenuHead.map(({ id, text }) => {
                return (
                    <Item  key={id} onClick={(e) => handlRightClick(e, id)}>
                        {text}
                    </Item> )
            })
        }
    </Menu>
    </Drawer>
  );
};

